import { useState } from 'react';
import Item from './Item';

export default function PackingList({
  items,
  handleDeleteItem,
  handleChangePacked,
  handleClearList,
}) {
  const [sortBy, setSortBy] = useState('input');

  if (!items.length) {
    return <p className='list'>Your packing list is empty.</p>;
  }

  let sortedItems;

  if (sortBy === 'input') sortedItems = items;
  else if (sortBy === 'description')
    sortedItems = items.sort((a, b) =>
      a.description.localeCompare(b.description),
    );
  else if (sortBy === 'packed')
    sortedItems = items.sort((a, b) => a.packed / 1 - b.packed / 1); // 0 - 1 -

  if (sortedItems.length === 1) {
    return (
      <p className='list'>
        Your packing list contains <strong>1 item</strong>.
      </p>
    );
  }

  return (
    <div className='list'>
      {sortedItems.length && (
        <>
          <ul>
            {sortedItems.map((item) => (
              <Item
                handleDeleteItem={handleDeleteItem}
                handleChangePacked={handleChangePacked}
                item={item}
                key={item.id}
              />
            ))}
          </ul>

          <div className='actions'>
            <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}>
              <option value='input'>Sort by input order</option>
              <option value='description'>Sort by description</option>
              <option value='packed'>Sort by packed status</option>
            </select>
            <button onClick={handleClearList}>Clear List</button>
          </div>
        </>
      )}
    </div>
  );
}
